
// © bull

//@version=5
indicator('SUPER3_Brahmastra', shorttitle='SUPER3_ Brahmastra', overlay=true,max_lines_count=500, max_bars_back=2000, max_boxes_count=500)

// User inputs
showTomorrowCPR = input(title='Show tomorrow\'s CPR', defval=true)
showHistoricalCPR = input(title='Show historical CPR', defval=true)
showWeeklyCPR = input(title='Show Weekly CPR', defval=true)
showR3wS3w = input(title='Show R3w & S3w', defval=true)
showR3S3 = input(title='Show R3 & S3', defval=true)
showPDHL = input(title='Show previous day\'s High & Low', defval=true)
showPDC = input(title='Show previous day\'s Close', defval=true)

// Defaults
// CPR Colors
cprColor = #FF6EFF
rColor = color.red
sColor = color.green
cColor = #3eecd5
wcprcolor = color.white

// Line style & Transparency
lStyle = plot.style_circles
lTransp = 35

//Fill Transparency
fTransp = 95

// Global Variables & Flags
// TODO : Update the No of Holidays
noOfHolidays = 12

// Global Functions
// TODO : Update the list of Holiday here in format YYYY, MM, DD, 09, 15 
// **09, 15 are session start hour & minutes
IsHoliday(_date) =>
    iff_1 = _date == timestamp(2020, 12, 25, 09, 15) ? true : false
    iff_2 = _date == timestamp(2020, 11, 30, 09, 15) ? true : iff_1
    iff_3 = _date == timestamp(2020, 11, 16, 09, 15) ? true : iff_2
    iff_4 = _date == timestamp(2020, 10, 02, 09, 15) ? true : iff_3
    iff_5 = _date == timestamp(2020, 05, 25, 09, 15) ? true : iff_4
    iff_6 = _date == timestamp(2020, 05, 01, 09, 15) ? true : iff_5
    iff_7 = _date == timestamp(2020, 04, 14, 09, 15) ? true : iff_6
    iff_8 = _date == timestamp(2020, 04, 10, 09, 15) ? true : iff_7
    iff_9 = _date == timestamp(2020, 04, 06, 09, 15) ? true : iff_8
    iff_10 = _date == timestamp(2020, 04, 02, 09, 15) ? true : iff_9
    iff_11 = _date == timestamp(2020, 03, 10, 09, 15) ? true : iff_10
    _date == timestamp(2020, 02, 21, 09, 15) ? true : iff_11

// Note: Week of Sunday=1...Saturday=7
IsWeekend(_date) =>
    dayofweek(_date) == 7 or dayofweek(_date) == 1

// Skip Weekend
SkipWeekend(_date) =>
    _d = dayofweek(_date)
    _mul = _d == 6 ? 3 : _d == 7 ? 2 : 1

    _date + _mul * 86400000

// Get Next Working Day
GetNextWorkingDay(_date) =>
    _dt = SkipWeekend(_date)

    for i = 1 to noOfHolidays by 1
        if IsHoliday(_dt)
            _dt := SkipWeekend(_dt)
            continue
        else
            break

    _dt

// Today's Session Start timestamp
y = year(timenow)
m = month(timenow)
d = dayofmonth(timenow)

// Start & End time for Today's CPR
start = timestamp(y, m, d, 09, 15)
end = start + 86400000

// Plot Today's CPR
shouldPlotToday = timenow > start

tom_start = start
tom_end = end

// Start & End time for Tomorrow's CPR
if shouldPlotToday
    tom_start := GetNextWorkingDay(start)
    tom_end := tom_start + 86400000
    tom_end

// Get series
getSeries(e, timeFrame) =>
    request.security(syminfo.tickerid, 'D', e, lookahead=barmerge.lookahead_on)
getwSeries(e, timeFrame) =>
    request.security(syminfo.tickerid, 'W', e, lookahead=barmerge.lookahead_on)

// Calculate Today's CPR
//Get High, Low and Close
H = getSeries(high[1], 'D')
L = getSeries(low[1], 'D')
C = getSeries(close[1], 'D')

// Pivot Range
P = (H + L + C) / 3
TC = (H + L) / 2
BC = P - TC + P

//plot(wP, color=color.white, linewidth = 1)
//plot(wTC, color=color.white, linewidth = 1)
//plot(wBC, color=color.white,  linewidth = 1)

// Resistance Levels
R3 = H + 2 * (P - L)
R2 = P + H - L
R1 = P * 2 - L

// Support Levels
S1 = P * 2 - H
S2 = P - (H - L)
S3 = L - 2 * (H - P)

Hw = getwSeries(high[1], 'W')
Lw = getwSeries(low[1], 'W')
Cw = getwSeries(close[1], 'W')

Pw = (Hw + Lw + Cw) / 3
TCw = (Hw + Lw) / 2
BCw = Pw - TCw + Pw

R3w = Hw + 2 * (Pw - Lw)
R2w = Pw + Hw - Lw
R1w = Pw * 2 - Lw

S1w = Pw * 2 - Hw
S2w = Pw - (Hw - Lw)
S3w = Lw - 2 * (Hw - Pw)

// Plot Today's CPR
if not IsHoliday(start) and not IsWeekend(start) and shouldPlotToday
    if showR3S3
        _r3 = line.new(start, R3, end, R3, xloc.bar_time, color=color.new(rColor, lTransp), width=3)
        line.delete(_r3[1])
    _r2 = line.new(start, R2, end, R2, xloc.bar_time, color=color.new(rColor, lTransp), width=3)
    line.delete(_r2[1])
    _r1 = line.new(start, R1, end, R1, xloc.bar_time, color=color.new(rColor, lTransp), width=3)
    line.delete(_r1[1])

    _tc = line.new(start, TC, end, TC, xloc.bar_time, color=color.new(cprColor, lTransp))
    line.delete(_tc[1])
    _p = line.new(start, P, end, P, xloc.bar_time, color=color.new(cprColor, lTransp))
    line.delete(_p[1])
    _bc = line.new(start, BC, end, BC, xloc.bar_time, color=color.new(cprColor, lTransp))
    line.delete(_bc[1])

    _s1 = line.new(start, S1, end, S1, xloc.bar_time, color=color.new(sColor, lTransp), width=3)
    line.delete(_s1[1])
    _s2 = line.new(start, S2, end, S2, xloc.bar_time, color=color.new(sColor, lTransp), width=3)
    line.delete(_s2[1])
    if showR3S3
        _s3 = line.new(start, S3, end, S3, xloc.bar_time, color=color.new(sColor, lTransp), width=3)
        line.delete(_s3[1])
    if showPDHL
        _pdh = line.new(start, H, end, H, xloc.bar_time, color=color.new(rColor, 0), style=line.style_solid, width=3)
        line.delete(_pdh[1])
        _pdl = line.new(start, L, end, L, xloc.bar_time, color=color.new(sColor, 0), style=line.style_solid, width=3)
        line.delete(_pdl[1])
    if showPDC
        _pdc = line.new(start, C, end, C, xloc.bar_time, color=color.new(cColor, 0), style=line.style_solid, width=3)
        line.delete(_pdc[1])

// Plot Today's Labels
if not IsHoliday(start) and not IsWeekend(start) and shouldPlotToday
    if showR3S3
        l_R3 = label.new(start, R3, text='R3', xloc=xloc.bar_time, textcolor=rColor, style=label.style_none)
        label.delete(l_R3[1])
    l_R2 = label.new(start, R2, text='R2', xloc=xloc.bar_time, textcolor=rColor, style=label.style_none)
    label.delete(l_R2[1])
    l_R1 = label.new(start, R1, text='R1', xloc=xloc.bar_time, textcolor=rColor, style=label.style_none)
    label.delete(l_R1[1])

    l_tc = label.new(start, TC, text='TC', xloc=xloc.bar_time, textcolor=cprColor, style=label.style_none)
    label.delete(l_tc[1])
    l_p = label.new(start, P, text='P', xloc=xloc.bar_time, textcolor=cprColor, style=label.style_none)
    label.delete(l_p[1])
    l_bc = label.new(start, BC, text='BC', xloc=xloc.bar_time, textcolor=cprColor, style=label.style_none)
    label.delete(l_bc[1])

    l_s1 = label.new(start, S1, text='S1', xloc=xloc.bar_time, textcolor=sColor, style=label.style_none)
    label.delete(l_s1[1])
    l_s2 = label.new(start, S2, text='S2', xloc=xloc.bar_time, textcolor=sColor, style=label.style_none)
    label.delete(l_s2[1])
    if showR3S3
        l_s3 = label.new(start, S3, text='S3', xloc=xloc.bar_time, textcolor=sColor, style=label.style_none)
        label.delete(l_s3[1])
    if showPDHL
        l_pdh = label.new(start, H, text='PD High', xloc=xloc.bar_time, textcolor=rColor, style=label.style_none)
        label.delete(l_pdh[1])
        l_pdl = label.new(start, L, text='PD Low', xloc=xloc.bar_time, textcolor=sColor, style=label.style_none)
        label.delete(l_pdl[1])
    if showPDC
        l_pdc = label.new(start, C, text='PD Close', xloc=xloc.bar_time, textcolor=cColor, style=label.style_none)
        label.delete(l_pdc[1])

// Plot Today's Weekly CPR
if not IsHoliday(start) and not IsWeekend(start) and showWeeklyCPR
    if showR3wS3w
        _r3w = line.new(start, R3w, end, R3w, xloc.bar_time, color=color.new(rColor, lTransp))
        line.delete(_r3w[1])
    _r2w = line.new(start, R2w, end, R2w, xloc.bar_time, color=color.new(rColor, lTransp))
    line.delete(_r2w[1])
    _r1w = line.new(start, R1w, end, R1w, xloc.bar_time, color=color.new(rColor, lTransp))
    line.delete(_r1w[1])

    _TCw = line.new(start, TCw, end, TCw, xloc.bar_time, color=color.blue, style=line.style_solid, width=3)
    line.delete(_TCw[1])
    _Pw = line.new(start, Pw, end, Pw, xloc.bar_time, color=color.blue, style=line.style_solid, width=3)
    line.delete(_Pw[1])
    _BCw = line.new(start, BCw, end, BCw, xloc.bar_time, color=color.blue, style=line.style_solid, width=3)
    line.delete(_BCw[1])

    _s1w = line.new(start, S1w, end, S1w, xloc.bar_time, color=color.new(sColor, lTransp))
    line.delete(_s1w[1])
    // _s2w = line.new(start, S2w, end, S2w, xloc.bar_time, color=color.new(sColor, lTransp))
    // line.delete(_s2w[1])
    if showR3wS3w
        _s3w = line.new(start, S3w, end, S3w, xloc.bar_time, color=color.new(sColor, lTransp))
        line.delete(_s3w[1])



// Calculate Tomorrow's CPR
// Get High, Low and Close
tH = getSeries(high, 'D')
tL = getSeries(low, 'D')
tC = getSeries(close, 'D')

// Pivot Range
tP = (tH + tL + tC) / 3
tTC = (tH + tL) / 2
tBC = tP - tTC + tP

// Resistance Levels
tR3 = tH + 2 * (tP - tL)
tR2 = tP + tH - tL
tR1 = tP * 2 - tL

// Support Levels
tS1 = tP * 2 - tH
tS2 = tP - (tH - tL)
tS3 = tL - 2 * (tH - tP)

// Plot Tomorrow's CPR
if showTomorrowCPR
    if showR3S3
        _t_r3 = line.new(tom_start, tR3, tom_end, tR3, xloc.bar_time, color=color.new(rColor, lTransp))
        line.delete(_t_r3[1])
    _t_r2 = line.new(tom_start, tR2, tom_end, tR2, xloc.bar_time, color=color.new(rColor, lTransp))
    line.delete(_t_r2[1])
    _t_r1 = line.new(tom_start, tR1, tom_end, tR1, xloc.bar_time, color=color.new(rColor, lTransp))
    line.delete(_t_r1[1])

    _t_tc = line.new(tom_start, tTC, tom_end, tTC, xloc.bar_time, color=color.new(cprColor, lTransp))
    line.delete(_t_tc[1])
    _t_p = line.new(tom_start, tP, tom_end, tP, xloc.bar_time, color=color.new(cprColor, lTransp))
    line.delete(_t_p[1])
    _t_bc = line.new(tom_start, tBC, tom_end, tBC, xloc.bar_time, color=color.new(cprColor, lTransp))
    line.delete(_t_bc[1])

    _t_s1 = line.new(tom_start, tS1, tom_end, tS1, xloc.bar_time, color=color.new(sColor, lTransp))
    line.delete(_t_s1[1])
    _t_s2 = line.new(tom_start, tS2, tom_end, tS2, xloc.bar_time, color=color.new(sColor, lTransp))
    line.delete(_t_s2[1])
    if showR3S3
        _t_s3 = line.new(tom_start, tS3, tom_end, tS3, xloc.bar_time, color=color.new(sColor, lTransp))
        line.delete(_t_s3[1])
    if showPDHL
        _pdth = line.new(tom_start, tH, tom_end, tH, xloc.bar_time, color=color.new(rColor, 0), style=line.style_solid, width=3)
        line.delete(_pdth[1])
        _pdtl = line.new(tom_start, tL, tom_end, tL, xloc.bar_time, color=color.new(sColor, 0), style=line.style_solid, width=3)
        line.delete(_pdtl[1])
    if showPDC
        _pdtc = line.new(tom_start, tC, tom_end, tC, xloc.bar_time, color=color.new(cColor, 0), style=line.style_solid, width=3)
        line.delete(_pdtc[1])

// Plot Tomorrow's Labels
if showTomorrowCPR
    if showR3S3
        l_t_r3 = label.new(tom_start, tR3, text='R3', xloc=xloc.bar_time, textcolor=rColor, style=label.style_none)
        label.delete(l_t_r3[1])
    l_t_r2 = label.new(tom_start, tR2, text='R2', xloc=xloc.bar_time, textcolor=rColor, style=label.style_none)
    label.delete(l_t_r2[1])
    l_t_r1 = label.new(tom_start, tR1, text='R1', xloc=xloc.bar_time, textcolor=rColor, style=label.style_none)
    label.delete(l_t_r1[1])

    l_t_tc = label.new(tom_start, tTC, text='TC', xloc=xloc.bar_time, textcolor=cprColor, style=label.style_none)
    label.delete(l_t_tc[1])
    l_t_p = label.new(tom_start, tP, text='P', xloc=xloc.bar_time, textcolor=cprColor, style=label.style_none)
    label.delete(l_t_p[1])
    l_t_bc = label.new(tom_start, tBC, text='BC', xloc=xloc.bar_time, textcolor=cprColor, style=label.style_none)
    label.delete(l_t_bc[1])

    l_t_s1 = label.new(tom_start, tS1, text='S1', xloc=xloc.bar_time, textcolor=sColor, style=label.style_none)
    label.delete(l_t_s1[1])
    l_t_s2 = label.new(tom_start, tS2, text='S2', xloc=xloc.bar_time, textcolor=sColor, style=label.style_none)
    label.delete(l_t_s2[1])
    if showR3S3
        l_t_s3 = label.new(tom_start, tS3, text='S3', xloc=xloc.bar_time, textcolor=sColor, style=label.style_none)
        label.delete(l_t_s3[1])
    if showPDHL
        l_pdth = label.new(tom_start, tH, text='PD High', xloc=xloc.bar_time, textcolor=rColor, style=label.style_none)
        label.delete(l_pdth[1])
        l_pdtl = label.new(tom_start, tL, text='PD Low', xloc=xloc.bar_time, textcolor=sColor, style=label.style_none)
        label.delete(l_pdtl[1])
    if showPDC
        l_pdtc = label.new(tom_start, tC, text='PD Close', xloc=xloc.bar_time, textcolor=cColor, style=label.style_none)
        label.delete(l_pdtc[1])

//Plot Historical CPR
p_r3 = plot(showHistoricalCPR ? showR3S3 ? R3 : na : na, title=' R3', color=rColor, style=lStyle, transp=lTransp)
p_r2 = plot(showHistoricalCPR ? R2 : na, title=' R2', color=rColor, style=lStyle, transp=lTransp)
p_r1 = plot(showHistoricalCPR ? R1 : na, title=' R1', color=rColor, style=lStyle, transp=lTransp)

p_cprTC = plot(showHistoricalCPR ? TC : na, title=' TC', color=cprColor, style=lStyle, transp=lTransp)
p_cprP = plot(showHistoricalCPR ? P : na, title=' P', color=cprColor, style=lStyle, transp=lTransp)
p_cprBC = plot(showHistoricalCPR ? BC : na, title=' BC', color=cprColor, style=lStyle, transp=lTransp)

s1 = plot(showHistoricalCPR ? S1 : na, title=' S1', color=sColor, style=lStyle, transp=lTransp)
s2 = plot(showHistoricalCPR ? S2 : na, title=' S2', color=sColor, style=lStyle, transp=lTransp)
s3 = plot(showHistoricalCPR ? showR3S3 ? S3 : na : na, title=' S3', color=sColor, style=lStyle, transp=lTransp)

fill(p_cprTC, p_cprBC, color=color.blue, transp=fTransp)

Little = ta.wma(close, 9)
short = ta.ema(close, 21)
middle = ta.ema(close, 89)
longest = ta.ema(close, 175)

//plot(Little, color=color.rgb(90, 249, 72),linewidth=2)
//plot(short, color=color.rgb(0, 33, 247),linewidth=2)
plot(middle, color=color.new(color.yellow, 0), linewidth=3)

//VWAP
PlotVWAP = input(title='Plot VWAP?', defval=true)
VWAPSource = input(title='VWAP Source', defval=hlc3)
VWAPrice = ta.vwap(VWAPSource)
plot(PlotVWAP ? VWAPrice : na, color=color.new(color.white, 0), title='VWAP', linewidth=2)

// Super Duper Trend

length = input(title='ATR Period', defval=10)
mult = input.float(title='ATR Multiplier', step=0.1, defval=2.2)
src = input(title='Source', defval=hlc3)
wicks = input(title='Take Wicks into Account ?', defval=true)
showLabels = input(title='Show Buy/Sell Labels ?', defval=true)
highlightState = input(title='Highlight State ?', defval=true)

atr = mult * ta.atr(length)

highPrice = wicks ? high : close
lowPrice = wicks ? low : close
doji4price = open == close and open == low and open == high

longStop = src - atr
longStopPrev = nz(longStop[1], longStop)

if longStop > 0
    if doji4price
        longStop := longStopPrev
        longStop
    else
        longStop := lowPrice[1] > longStopPrev ? math.max(longStop, longStopPrev) : longStop
        longStop
else
    longStop := longStopPrev
    longStop

shortStop = src + atr
shortStopPrev = nz(shortStop[1], shortStop)

if shortStop > 0
    if doji4price
        shortStop := shortStopPrev
        shortStop
    else
        shortStop := highPrice[1] < shortStopPrev ? math.min(shortStop, shortStopPrev) : shortStop
        shortStop
else
    shortStop := shortStopPrev
    shortStop

var int dir = 1
dir := dir == -1 and highPrice > shortStopPrev ? 1 : dir == 1 and lowPrice < longStopPrev ? -1 : dir

var color longColor = color.green
var color shortColor = color.red

//longStopPlot = plot(dir == 1 ? longStop : na, title="Long Stop", style=plot.style_linebr, linewidth=2, color=longColor)
buySignal = dir == 1 and dir[1] == -1
plotshape(buySignal ? longStop : na, title='Long Stop Start', location=location.absolute, style=shape.circle, size=size.tiny, color=color.new(longColor, 0))
plotshape(buySignal and showLabels ? longStop : na, title='Buy Label', text='Buy', location=location.absolute, style=shape.labelup, size=size.tiny, color=color.new(longColor, 0), textcolor=color.new(color.white, 0))

//shortStopPlot = plot(dir == 1 ? na : shortStop, title="Short Stop", style=plot.style_linebr, linewidth=2, color=shortColor)
sellSignal = dir == -1 and dir[1] == 1
plotshape(sellSignal ? shortStop : na, title='Short Stop Start', location=location.absolute, style=shape.circle, size=size.tiny, color=color.new(shortColor, 0))
plotshape(sellSignal and showLabels ? shortStop : na, title='Sell Label', text='Sell', location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.new(shortColor, 0), textcolor=color.new(color.white, 0))

midPricePlot = plot(ohlc4, title='', style=plot.style_circles, linewidth=0, display=display.none, editable=false)

//longFillColor = highlightState ? (dir == 1 ? longColor : na) : na
//shortFillColor = highlightState ? (dir == -1 ? shortColor : na) : na
//fill(midPricePlot, longStopPlot, title="Long State Filling", color=longFillColor)
//fill(midPricePlot, shortStopPlot, title="Short State Filling", color=shortFillColor)

changeCond = dir != dir[1]
alertcondition(changeCond, title='Alert: SuperTrend Direction Change', message='SuperTrend has changed direction!\nSymbol: {{exchange}}:{{ticker}}\nPrice: {{close}}')
alertcondition(buySignal, title='Alert: SuperTrend Buy', message='SuperTrend Buy!\nSymbol: {{exchange}}:{{ticker}}\nPrice: {{close}}')
alertcondition(sellSignal, title='Alert: SuperTrend Sell', message='SuperTrend Sell!\nSymbol: {{exchange}}:{{ticker}}\nPrice: {{close}}')

// Parabolic SAR

start2 = input.float(title='Start', step=0.001, defval=0.02)
increment = input.float(title='Increment', step=0.001, defval=0.02)
maximum = input.float(title='Maximum', step=0.01, defval=0.2)
width1 = input.int(title='Point Width', minval=1, defval=2)
highlightStartPoints = input(title='Highlight Start Points ?', defval=true)
showLabels1 = input(title='Show Buy/Sell Labels ?', defval=true)
highlightState1 = input(title='Highlight State ?', defval=true)

psar = ta.sar(start2, increment, maximum)
dir1 = psar < close ? 1 : -1

psarColor = dir1 == 1 ? #33fb06 : #fd0202
//psarPlot = plot(psar, title="PSAR", style=plot.style_circles, linewidth=width1, color=psarColor, transp=0)

var color longColor1 = color.green
var color shortColor1 = color.red

buySignal1 = dir1 == 1 and dir1[1] == -1
//plotshape(buySignal and highlightStartPoints ? psar : na, title="Long Start", location=location.absolute, style=shape.circle, size=size.tiny, color=longColor1, transp=0)
//plotshape(buySignal and showLabels1 ? psar : na, title="Buy Label", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=longColor1, textcolor=color.white, transp=0)

sellSignal1 = dir1 == -1 and dir1[1] == 1
//plotshape(sellSignal and highlightStartPoints ? psar : na, title="Short Start", location=location.absolute, style=shape.circle, size=size.tiny, color=shortColor1, transp=0)
//plotshape(sellSignal and showLabels1 ? psar : na, title="Sell Label", text="Sell", location=location.absolute, style=shape.labeldown, size=size.tiny, color=shortColor1, textcolor=color.white, transp=0)

midPricePlot1 = plot(ohlc4, title='', display=display.none)

//fillColor = highlightState1 ? (dir1 == 1 ? longColor1 : shortColor1) : na
//fill(midPricePlot1, psarPlot, title="Trade State Filling", color=fillColor)

changeCond1 = dir1 != dir1[1]
alertcondition(changeCond1, title='Alert: PSAR Direction Change', message='PSAR has changed direction!')
alertcondition(buySignal1, title='Alert: PSAR Long', message='PSAR Long')
alertcondition(sellSignal1, title='Alert: PSAR Short', message='PSAR Sell')

// RSI bar color 

//src3 = close, len = input(14, minval=1, title="Length")
//up = rma(max(change(src3), 0), len)
//down = rma(-min(change(src3), 0), len)
//rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))

//coloring method below

//src1 = close, len1 = input(50, minval=1, title="UpLevel")
//src2 = close, len2 = input(50, minval=1, title="DownLevel")
//isup() => rsi > len1
//isdown() => rsi < len2
//barcolor(isup() ?color.rgb(2, 249, 10) : isdown() ? color.rgb(249, 4, 4) : na )

src5 = close
len = input.int(14, minval=1, title='Length')
//coloring user input
src1 = close
len1 = input.int(53, minval=1, title='Overbought')
src2 = close
len2 = input.int(47, minval=1, title='Oversold')
src3 = close
len11 = input.int(80, minval=1, title='Very Overbought')
src4 = close
len22 = input.int(25, minval=1, title='Very Oversold')

//rsi processing
up = ta.rma(math.max(ta.change(src5), 0), len)
down = ta.rma(-math.min(ta.change(src5), 0), len)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - 100 / (1 + up / down)

//coloring function
isBought() =>
    rsi > len1 and rsi < len11
isSold() =>
    rsi < len2 and rsi > len22
isVeryBought() =>
    rsi > len11 and rsi > len1
isVerySold() =>
    rsi < len22 and rsi < len2

barcolor(isBought() ? color.rgb(4, 247, 13) : isSold() ? color.rgb(246, 7, 7) : isVeryBought() ? color.rgb(255, 255, 255) : isVerySold() ? color.rgb(252, 228, 7) : na)

// end RSI Bar Color 

//  Single Trend Ribbon basis MACD

fastLength = input.int(12, minval=1, title='Fast Length')
slowLength = input.int(26, minval=1, title='Slow Length')
fastMA = ta.ema(src, fastLength)
slowMA = ta.ema(src, slowLength)
macd = fastMA - slowMA
//plot(macd, title="MACD",  color.white, linewidth=2, transp=0)

// Signal
signalLength = input.int(9, minval=1, title='Signal Length')
signal = ta.ema(macd, signalLength)
lookback = input.int(1, minval=0, title='Color Lookback (0 to disable)')
signalColor = lookback == 0 ? #009933 : ta.rising(signal, lookback) ? #5cd65c : ta.falling(signal, lookback) ? #ff3333 : #ff3333
plotchar(signal, char='¦', title='Signal', color=signalColor, location=location.bottom, size=size.tiny, transp=0)

// Bollinger Band

// Draw channel.
len10 = input(20)
channelType = input.string(defval='Bollinger', title='Channel Type', options=['NONE', 'Donchian', 'Bollinger', 'Envelope'])
channelLen = input.int(14, minval=1, title='Channel Length')
envPer = input.float(4, title='Envelope %', minval=0) / 100

getChannels(src, len10) =>
    if channelType == 'Bollinger'
        ma = ta.ema(src, len10)
        dev = ta.stdev(src, len10)
        bbUp = ma + 2 * dev
        bbDown = ma - 2 * dev
        [bbUp, bbDown]
    else
        if channelType == 'Donchian'
            donUp = ta.highest(high[1], len10)
            donDown = ta.lowest(low[1], len10)
            [donUp, donDown]
        else
            if channelType == 'Envelope'
                ma = ta.ema(src, len10)
                envUp = ma * (1 + envPer)
                envDown = ma * (1 - envPer)
                [envUp, envDown]
            else
                [na, na]

[upperchannel, lowerchannel] = getChannels(src, len10)
//u = plot(upperchannel, linewidth=1, color=color.rgb(228, 234, 234, 41), title="Band High")
//plot(avg(upperchannel, lowerchannel), linewidth=2, color=color.rgb(1, 237, 249), title="Band Middle")
//l = plot(lowerchannel, linewidth=1, color=color.rgb(199, 205, 205, 51), title="Band Low")
//fill(u, l)

// End of bollinger Band 

// Super Xtrend 

amplitude = input(title='Amplitude', defval=2)
channelDeviation = input(title='Channel Deviation', defval=2)
showArrows = input(title='Show Arrows', defval=true)
showChannels = input(title='Show Channels', defval=true)

var int trend = 0
var int nextTrend = 0
var float maxLowPrice = nz(low[1], low)
var float minHighPrice = nz(high[1], high)

var float up1 = 0.0
var float down1 = 0.0
float atrHigh = 0.0
float atrLow = 0.0
float arrowUp = na
float arrowDown = na

atr2 = ta.atr(100) / 2
dev = channelDeviation * atr2

highPrice1 = high[math.abs(ta.highestbars(amplitude))]
lowPrice1 = low[math.abs(ta.lowestbars(amplitude))]
highma = ta.sma(high, amplitude)
lowma = ta.sma(low, amplitude)

if nextTrend == 1
    maxLowPrice := math.max(lowPrice1, maxLowPrice)

    if highma < maxLowPrice and close < nz(low[1], low)
        trend := 1
        nextTrend := 0
        minHighPrice := highPrice1
        minHighPrice
else
    minHighPrice := math.min(highPrice1, minHighPrice)

    if lowma > minHighPrice and close > nz(high[1], high)
        trend := 0
        nextTrend := 1
        maxLowPrice := lowPrice1
        maxLowPrice

if trend == 0
    if not na(trend[1]) and trend[1] != 0
        up1 := na(down1[1]) ? down1 : down1[1]
        arrowUp := up - atr2
        arrowUp
    else
        up1 := na(up1[1]) ? maxLowPrice : math.max(maxLowPrice, up1[1])
        up1
    atrHigh := up1 + dev
    atrLow := up1 - dev
    atrLow
else
    if not na(trend[1]) and trend[1] != 1
        down1 := na(up1[1]) ? up1 : up1[1]
        arrowDown := down1 + atr2
        arrowDown
    else
        down1 := na(down1[1]) ? minHighPrice : math.min(minHighPrice, down1[1])
        down1
    atrHigh := down1 + dev
    atrLow := down1 - dev
    atrLow

ht = trend == 0 ? up1 : down1

var color buyColor = color.rgb(59, 251, 6)
var color sellColor = color.red

htColor = trend == 0 ? buyColor : sellColor
htPlot = plot(ht, title='ultra', linewidth=2, color=htColor)

buySignal2 = not na(arrowUp) and trend == 0 and trend[1] == 1
sellSignal2 = not na(arrowDown) and trend == 1 and trend[1] == 0

//plotshape(showArrows and buySignal2 ? atrLow : na, title="Arrow Up", style=shape.arrowup, location=location.absolute, size=size.large, color=buyColor)
//plotshape(showArrows and sellSignal2 ? atrHigh : na, title="Arrow Down", style=shape.arrowdown, location=location.absolute, size=size.large, color=sellColor)

alertcondition(buySignal2, title='Alert: ultra Buy', message='ultra Buy')
alertcondition(sellSignal2, title='Alert: ultra Sell', message='ultra Sell')
// End Xtrend

// SonarLab Oreder Blocks
max_boxes_count=20

_v = input.string("1.0.2", title="Version", options=["1.0.2"], group="Sonarlab.io", tooltip="This is a free script based on our premium Smart Money Concepts (SMC) indicator." )
sens = input.int(28, minval=1, title='Sensitivity', group='Order Block', tooltip='Lower the sensitivity to show more order blocks. A higher sensitivity will show less order blocks.')
sens /= 100

// OB
OBMitigationType = input.string("Close", title="OB Mitigation Type", options=["Close", "Wick"], group="Order Block", tooltip="Choose how Order Blocks are mitigated")
OBBullMitigation = OBMitigationType=="Close" ? close[1] : low
OBBearMitigation = OBMitigationType=="Close" ? close[1] : high

//OB Colors
col_bullish = input.color(#5db49e, title="Bullish OB Border", inline="a", group="Order Block")
col_bullish_ob = input.color(color.new(#64C4AC, 85), title="Background", inline="a", group="Order Block")

col_bearish = input.color(#4760bb, title="Bearish OB Border", inline="b", group="Order Block")
col_bearish_ob = input.color(color.new(#506CD3, 85), title="Background", inline="b", group="Order Block")

// Alerts
buy_alert = input.bool(title='Buy Signal', defval=true, group='Alerts', tooltip='An alert will be sent when price goes below the top of a bullish order block.')
sell_alert = input.bool(title='Sell Signal', defval=true, group='Alerts', tooltip='An alert will be sent when price goes above the bottom of a bearish order block.')

// Delacring Variables
bool ob_created = false
bool ob_created_bull = false
var int cross_index = na

// Declaring Box Arrays
var box drawlongBox = na
var longBoxes = array.new_box()
var box drawShortBox = na
var shortBoxes = array.new_box()

// Custom Rate of Change (ROC) calculation. This is to calculate high momentum moves in the market.
pc = (open - open[4]) / open[4] * 100

// If the ROC crossover our Sensitivty input - Then create an Order Block
// Sensitivty is negative as this is a Bearish OB
if ta.crossunder(pc, -sens)
    ob_created := true
    cross_index := bar_index
    cross_index

// If the ROC crossover our Sensitivty input - Then create an Order Block
if ta.crossover(pc, sens)
    ob_created_bull := true
    cross_index := bar_index
    cross_index

// -------------------------------
// Bearish OB Creation
// -------------------------------
// Check if we should create a OB, Also check if we haven't created an OB in the last 5 candles.
if ob_created and cross_index - cross_index[1] > 5
    float last_green = 0
    float highest = 0
    // Loop through the most recent candles and find the first GREEN (Bullish) candle. We will place our OB here.
    for i = 4 to 15 by 1
        if close[i] > open[i]
            last_green := i
            break
    // Draw our OB on that candle - then push the box into our box arrays.
    drawShortBox := box.new(left=bar_index[last_green], top=high[last_green], bottom=low[last_green], right=bar_index[last_green], bgcolor=col_bearish_ob, border_color=col_bearish, extend=extend.right)
    array.push(shortBoxes, drawShortBox)

// -------------------------------
// Bullish OB Creation
// -------------------------------
// Check if we should create a OB, Also check if we haven't created an OB in the last 5 candles.
if ob_created_bull and cross_index - cross_index[1] > 5
    float last_red = 0
    float highest = 0
    // Loop through the most recent candles and find the first RED (Bearish) candle. We will place our OB here.
    for i = 4 to 15 by 1
        if close[i] < open[i]
            last_red := i
            break
    // Draw our OB on that candle - then push the box into our box arrays.
    drawlongBox := box.new(left=bar_index[last_red], top=high[last_red], bottom=low[last_red], right=bar_index[last_red], bgcolor=col_bullish_ob, border_color=col_bullish, extend=extend.right)
    array.push(longBoxes, drawlongBox)

// ----------------- Bearish Order Block -------------------
// Clean up OB boxes and place alerts
if array.size(shortBoxes) > 0
    for i = array.size(shortBoxes) - 1 to 0 by 1
        sbox = array.get(shortBoxes, i)
        top = box.get_top(sbox)
        bot = box.get_bottom(sbox)
        // If the two last closes are above the high of the bearish OB - Remove the OB
        if OBBearMitigation > top
            array.remove(shortBoxes, i)
            box.delete(sbox)
        // Alerts
        if high > bot and sell_alert
            alert('Price inside Bearish OB', alert.freq_once_per_bar)

// ----------------- Bullish Clean Up -------------------
// Clean up OB boxes and place alerts
if array.size(longBoxes) > 0
    for i = array.size(longBoxes) - 1 to 0 by 1
        sbox = array.get(longBoxes, i)
        bot = box.get_bottom(sbox)
        top = box.get_top(sbox)
        // If the two last closes are below the low of the bullish OB - Remove the OB
        if OBBullMitigation < bot
            array.remove(longBoxes, i)
            box.delete(sbox)
        // Alerts
        if low < top and buy_alert
            alert('Price inside Bullish OB', alert.freq_once_per_bar)

// Market Structure Break & Order Block

settings = "Settings"
zigzag_len = input.int(9, "ZigZag Length", group=settings)
show_zigzag = input.bool(true, "Show Zigzag", group=settings)
fib_factor = input.float(0.33, "Fib Factor for breakout confirmation", 0, 1, 0.01, group=settings)

tooltip_text = "Some timeframes may not be displayed in current timeframe. Zigzag lines only shows in current timeframe."
time_frame= input.string("Chart", "Timeframe", ["Chart", "5m", "15m", "30m", "1h", "2h", "4h", "D"], tooltip=tooltip_text)

tf = switch time_frame
    "5m" => "5"
    "15m" => "15"
    "30m" => "30"
    "1h" => "60"
    "2h" => "120"
    "4h" => "240"
    "D" => "D"
    => timeframe.period

text_size = input.string(size.tiny, "Text Size", [size.tiny, size.small, size.normal, size.large, size.huge])

bu_ob_inline_color = "Bu-OB Colors"
be_ob_inline_color = "Be-OB Colors"
bu_bb_inline_color = "Bu-BB Colors"
be_bb_inline_color = "Be-BB Colors"

bu_ob_display_settings = "Bu-OB Display Settings"
bu_ob_color = input.color(color.new(color.green, 70), "Color", group=bu_ob_display_settings, inline=bu_ob_inline_color)
bu_ob_border_color = input.color(color.green, "Border Color", group=bu_ob_display_settings, inline=bu_ob_inline_color)
bu_ob_text_color = input.color(color.green, "Text Color", group=bu_ob_display_settings, inline=bu_ob_inline_color)

be_ob_display_settings = "Be-OB Display Settings"
be_ob_color = input.color(color.new(color.red, 70), "Color", group=be_ob_display_settings, inline=be_ob_inline_color)
be_ob_border_color = input.color(color.red, "Border Color", group=be_ob_display_settings, inline=be_ob_inline_color)
be_ob_text_color = input.color(color.red, "Text Color", group=be_ob_display_settings, inline=be_ob_inline_color)

bu_bb_display_settings = "Bu-BB & Bu-MB Display Settings"
bu_bb_color = input.color(color.new(color.green, 70), "Color", group=bu_bb_display_settings, inline=bu_bb_inline_color)
bu_bb_border_color = input.color(color.green, "Border Color", group=bu_bb_display_settings, inline=bu_bb_inline_color)
bu_bb_text_color = input.color(color.green, "Text Color", group=bu_bb_display_settings, inline=bu_bb_inline_color)

be_bb_display_settings = "Be-BB & Be-MB Display Settings"
be_bb_color = input.color(color.new(color.red, 70), "Color", group=be_bb_display_settings, inline=be_bb_inline_color)
be_bb_border_color = input.color(color.red, "Border Color", group=be_bb_display_settings, inline=be_bb_inline_color)
be_bb_text_color = input.color(color.red, "Text Color", group=be_bb_display_settings, inline=be_bb_inline_color)

var float[] high_points_arr = array.new_float(5)
var int[] high_index_arr = array.new_int(5)
var float[] low_points_arr = array.new_float(5)
var int[] low_index_arr = array.new_int(5)

var box[] bu_ob_boxes = array.new_box(5)
var box[] be_ob_boxes = array.new_box(5)
var box[] bu_bb_boxes = array.new_box(5)
var box[] be_bb_boxes = array.new_box(5)

f_get_high(ind) =>
    [array.get(high_points_arr, array.size(high_points_arr) - 1 - ind), array.get(high_index_arr, array.size(high_index_arr) - 1 - ind)]

f_get_low(ind) =>
    [array.get(low_points_arr, array.size(low_points_arr) - 1 - ind), array.get(low_index_arr, array.size(low_index_arr) - 1 - ind)]

f_main1() =>
    to_up = high >= ta.highest(zigzag_len)
    to_down = low <= ta.lowest(zigzag_len)
    
    trend = 1
    trend := nz(trend[1], 1)
    trend := trend == 1 and to_down ? -1 : trend == -1 and to_up ? 1 : trend
    
    last_trend_up_since = ta.barssince(to_up[1])
    low_val = ta.lowest(nz(last_trend_up_since > 0 ? last_trend_up_since : 1, 1))
    low_index = bar_index - ta.barssince(low_val == low)
    
    last_trend_down_since = ta.barssince(to_down[1])
    high_val = ta.highest(nz(last_trend_down_since > 0 ? last_trend_down_since : 1, 1))
    high_index = bar_index - ta.barssince(high_val == high)
    
    if ta.change(trend) != 0
        if trend == 1
            array.push(low_points_arr, low_val)
            array.push(low_index_arr, low_index)
        if trend == -1
            array.push(high_points_arr, high_val)
            array.push(high_index_arr, high_index)
    
    [h0, h0i] = f_get_high(0)
    [h1, h1i] = f_get_high(1)
    
    [l0, l0i] = f_get_low(0)
    [l1, l1i] = f_get_low(1)
    
    market = 1
    market := nz(market[1], 1)
    last_l0 = ta.valuewhen(ta.change(market) != 0, l0, 0)
    last_h0 = ta.valuewhen(ta.change(market) != 0, h0, 0)
    market := last_l0 == l0 or last_h0 == h0 ? market : market == 1 and l0 < l1 and l0 < l1 - math.abs(h0 - l1) * fib_factor ? -1 : market == -1 and h0 > h1 and h0 > h1 + math.abs(h1 - l0) * fib_factor ? 1 : market
    
    // For alert
    alert_market = 1
    alert_market := nz(alert_market[1], 1)
    alert_market := last_l0 == l0 or last_h0 == h0 ? alert_market : alert_market == 1 and trend == -1 and close < l0 and close < l0 - math.abs(h0 - l0) * fib_factor ? -1 : alert_market == -1 and trend == 1 and close > h0 and close > h0 + math.abs(h0 - l0) * fib_factor ? 1 : alert_market
    
    bu_ob_index = bar_index
    bu_ob_index := nz(bu_ob_index[1], bar_index)
    for i=h1i to l0i[zigzag_len]
        index = bar_index - i 
        if open[index] > close[index]
            bu_ob_index := bar_index[index]
    
    bu_ob_since = bar_index - bu_ob_index
    
    be_ob_index = bar_index
    be_ob_index := nz(be_ob_index[1], bar_index)
    for i=l1i to h0i[zigzag_len]
        index = bar_index - i 
        if open[index] < close[index]
            be_ob_index := bar_index[index]
    
    be_ob_since = bar_index - be_ob_index
    
    be_bb_index = bar_index
    be_bb_index := nz(be_bb_index[1], bar_index)
    for i=h1i - zigzag_len to l1i
        index = bar_index - i
        if open[index] > close[index]
            be_bb_index := bar_index[index]
    
    be_bb_since = bar_index - be_bb_index
    
    bu_bb_index = bar_index
    bu_bb_index := nz(bu_bb_index[1], bar_index)
    for i=l1i - zigzag_len to h1i
        index = bar_index - i
        if open[index] < close[index]
            bu_bb_index := bar_index[index]
    
    bu_bb_since = bar_index - bu_bb_index
    
    
    bu_ob_since_high = high[bu_ob_since]
    bu_ob_since_low = low[bu_ob_since]
    be_ob_since_high = high[be_ob_since]
    be_ob_since_low = low[be_ob_since]
    be_bb_since_high = high[be_bb_since]
    be_bb_since_low = low[be_bb_since]
    bu_bb_since_high = high[bu_bb_since]
    bu_bb_since_low = low[bu_bb_since]
    
    [trend, h0i, h0, l0i, l0, market, h1i, h1, l1i, l1, bu_ob_since_high, bu_ob_since_low, be_ob_since_high, be_ob_since_low]
    

f_main2() =>
    to_up = high >= ta.highest(zigzag_len)
    to_down = low <= ta.lowest(zigzag_len)
    
    trendms = 1
    trendms := nz(trendms[1], 1)
    trendms := trendms == 1 and to_down ? -1 : trendms == -1 and to_up ? 1 : trendms
    
    last_trendms_up_since = ta.barssince(to_up[1])
    low_val = ta.lowest(nz(last_trendms_up_since > 0 ? last_trendms_up_since : 1, 1))
    low_index = bar_index - ta.barssince(low_val == low)
    
    last_trendms_down_since = ta.barssince(to_down[1])
    high_val = ta.highest(nz(last_trendms_down_since > 0 ? last_trendms_down_since : 1, 1))
    high_index = bar_index - ta.barssince(high_val == high)
    
    if ta.change(trendms) != 0
        if trendms == 1
            array.push(low_points_arr, low_val)
            array.push(low_index_arr, low_index)
        if trendms == -1
            array.push(high_points_arr, high_val)
            array.push(high_index_arr, high_index)
    
    [h0, h0i] = f_get_high(0)
    [h1, h1i] = f_get_high(1)
    
    [l0, l0i] = f_get_low(0)
    [l1, l1i] = f_get_low(1)
    
    market = 1
    market := nz(market[1], 1)
    last_l0 = ta.valuewhen(ta.change(market) != 0, l0, 0)
    last_h0 = ta.valuewhen(ta.change(market) != 0, h0, 0)
    market := last_l0 == l0 or last_h0 == h0 ? market : market == 1 and l0 < l1 and l0 < l1 - math.abs(h0 - l1) * fib_factor ? -1 : market == -1 and h0 > h1 and h0 > h1 + math.abs(h1 - l0) * fib_factor ? 1 : market
    
    // For alert
    alert_market = 1
    alert_market := nz(alert_market[1], 1)
    alert_market := last_l0 == l0 or last_h0 == h0 ? alert_market : alert_market == 1 and trendms == -1 and close < l0 and close < l0 - math.abs(h0 - l0) * fib_factor ? -1 : alert_market == -1 and trendms == 1 and close > h0 and close > h0 + math.abs(h0 - l0) * fib_factor ? 1 : alert_market
    
    bu_ob_index = bar_index
    bu_ob_index := nz(bu_ob_index[1], bar_index)
    for i=h1i to l0i[zigzag_len]
        index = bar_index - i 
        if open[index] > close[index]
            bu_ob_index := bar_index[index]
    
    bu_ob_since = bar_index - bu_ob_index
    
    be_ob_index = bar_index
    be_ob_index := nz(be_ob_index[1], bar_index)
    for i=l1i to h0i[zigzag_len]
        index = bar_index - i 
        if open[index] < close[index]
            be_ob_index := bar_index[index]
    
    be_ob_since = bar_index - be_ob_index
    
    be_bb_index = bar_index
    be_bb_index := nz(be_bb_index[1], bar_index)
    for i=h1i - zigzag_len to l1i
        index = bar_index - i
        if open[index] > close[index]
            be_bb_index := bar_index[index]
    
    be_bb_since = bar_index - be_bb_index
    
    bu_bb_index = bar_index
    bu_bb_index := nz(bu_bb_index[1], bar_index)
    for i=l1i - zigzag_len to h1i
        index = bar_index - i
        if open[index] < close[index]
            bu_bb_index := bar_index[index]
    
    bu_bb_since = bar_index - bu_bb_index
    
    
    bu_ob_since_high = high[bu_ob_since]
    bu_ob_since_low = low[bu_ob_since]
    be_ob_since_high = high[be_ob_since]
    be_ob_since_low = low[be_ob_since]
    be_bb_since_high = high[be_bb_since]
    be_bb_since_low = low[be_bb_since]
    bu_bb_since_high = high[bu_bb_since]
    bu_bb_since_low = low[bu_bb_since]
    
    [alert_market, be_bb_since_high, be_bb_since_low, bu_bb_since_high, bu_bb_since_low, bu_ob_index, bu_bb_index, be_ob_index, be_bb_index]

[trendms, h0i, h0, l0i, l0, market, h1i, h1, l1i, l1, bu_ob_since_high, bu_ob_since_low, be_ob_since_high, be_ob_since_low] = request.security(syminfo.tickerid, tf, f_main1())
[alert_market, be_bb_since_high, be_bb_since_low, bu_bb_since_high, bu_bb_since_low, bu_ob_index, bu_bb_index, be_ob_index, be_bb_index] = request.security(syminfo.tickerid, tf, f_main2())

// Be_bb_since olanlar değişecek be_ob_index ler eklenecek

if ta.change(trendms) != 0 and show_zigzag
    if trendms == 1
        line.new(h0i, h0, l0i, l0)
    if trendms == -1
        line.new(l0i, l0, h0i, h0)

if ta.change(market) != 0
    if market == 1
        line.new(h1i, h1, h0i, h1, color=color.green, width=2)
        label.new(int(math.avg(h1i, l0i)), h1, "MSB", color=color.new(color.black, 100), style=label.style_label_down, textcolor=color.green, size=size.small)
        bu_ob = box.new(bu_ob_index, bu_ob_since_high, bar_index + 10, bu_ob_since_low, bgcolor=bu_ob_color, border_color=bu_ob_border_color, text="Bu-OB", text_color=bu_ob_text_color, text_halign=text.align_right, text_size=text_size)
        bu_bb = box.new(bu_bb_index, bu_bb_since_high, bar_index + 10, bu_bb_since_low, bgcolor=bu_bb_color, border_color=bu_bb_border_color, text=l0 < l1 ? "Bu-BB" : "Bu-MB", text_color=bu_bb_text_color, text_halign=text.align_right, text_size=text_size)
        array.push(bu_ob_boxes, bu_ob)
        array.push(bu_bb_boxes, bu_bb)
    if market == -1
        line.new(l1i, l1, l0i, l1, color=color.red, width=2)
        label.new(int(math.avg(l1i, h0i)), l1, "MSB", color=color.new(color.black, 100), style=label.style_label_up, textcolor=color.red, size=size.small)
        be_ob = box.new(be_ob_index, be_ob_since_high, bar_index + 10, be_ob_since_low, bgcolor=be_ob_color, border_color=be_ob_border_color, text="Be-OB", text_color=be_ob_text_color, text_halign=text.align_right, text_size=text_size)
        be_bb = box.new(be_bb_index, be_bb_since_high, bar_index + 10, be_bb_since_low, bgcolor=be_bb_color, border_color=be_bb_border_color, text=h0 > h1 ? "Be-BB" : "Be-MB", text_color=be_bb_text_color, text_halign=text.align_right, text_size=text_size)
        array.push(be_ob_boxes, be_ob)
        array.push(be_bb_boxes, be_bb)

for bull_ob in bu_ob_boxes
    bottom = box.get_bottom(bull_ob)
    if close < bottom
        box.delete(bull_ob)
    else if array.size(bu_ob_boxes) == 5
        box.delete(array.shift(bu_ob_boxes))
    else
        box.set_right(bull_ob, bar_index + 10)
    
for bear_ob in be_ob_boxes
    top = box.get_top(bear_ob)
    if close > top
        box.delete(bear_ob)
    else if array.size(be_ob_boxes) == 5
        box.delete(array.shift(be_ob_boxes))
    else
        box.set_right(bear_ob, bar_index + 10)
        
for bear_bb in be_bb_boxes
    top = box.get_top(bear_bb)
    if close > top
        box.delete(bear_bb)
    else if array.size(be_bb_boxes) == 5
        box.delete(array.shift(be_bb_boxes))
    else
        box.set_right(bear_bb, bar_index + 10)
        
for bull_bb in bu_bb_boxes
    bottom = box.get_bottom(bull_bb)
    if close < bottom
        box.delete(bull_bb)
    else if array.size(bu_bb_boxes) == 5
        box.delete(array.shift(bu_bb_boxes))
    else
        box.set_right(bull_bb, bar_index + 10)
        
if ta.change(alert_market) != 0
    alert("MSB", alert.freq_once_per_bar)

//
//ADX Table

adxlen = input(14, title="ADX Smoothing")
dilen = input(14, title="DI Length")
dirmov(len) =>
	up = ta.change(high)
	down = -ta.change(low)
	plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
	minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
	truerange = ta.rma(ta.tr, len)
	plus = fixnan(100 * ta.rma(plusDM, len) / truerange)
	minus = fixnan(100 * ta.rma(minusDM, len) / truerange)
	[plus, minus]
adx(dilen, adxlen) =>
	[plus, minus] = dirmov(dilen)
	sum = plus + minus
	adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen)
sig = adx(dilen, adxlen)

color i_TriggerBGColor = input(defval = color.gray, title = "Trigger Time Background Color")
color i_TriggerTxtColor = input(defval = color.white,title = "Trigger Time Text Color")

color i_TradingBGColor = input(defval = color.blue,title = "Trading Time Background Color")
color i_TradingTxtColor = input(defval = color.white,title = "Trading Time Text Color")

color i_OtherBGColor = input(defval = color.gray,title = "Other Time Background Color")
color i_OtherTxtColor = input(defval = color.white,title = "Other Time Text Color")

i_decimal = input(defval = 2, title = "Decimal points")


var table adxDisplay = table.new(position.bottom_right, 3, 4, bgcolor = color.gray, frame_width = 2, frame_color = color.black)

adx3 = request.security(syminfo.tickerid, '3', sig)
adx5 = request.security(syminfo.tickerid, '5', sig)
adx15 = request.security(syminfo.tickerid, '15', sig)




if barstate.islast

    ADXformatStructure = '#.'

    for i = 1 to i_decimal
        ADXformatStructure += '0'
    

    color BGColor3 = i_OtherBGColor
    color BGColor5 = i_OtherBGColor
    color BGColor15 = i_OtherBGColor

    
    color TxtColor3 = i_OtherTxtColor
    color TxtColor5 = i_OtherTxtColor
    color TxtColor15 = i_OtherTxtColor



    switch timeframe.period
        "3" => 
            BGColor3 := i_TriggerBGColor
            TxtColor3 := i_TriggerTxtColor
        "5" => 
            BGColor5 := i_TriggerBGColor
            TxtColor5 := i_TriggerTxtColor
           
                
        "15" => 
            BGColor15 := i_TriggerBGColor
            TxtColor15 := i_TriggerTxtColor


    // We only populate the table on the last bar.
    table.cell(adxDisplay, 0, 0, "ADX 3m: " + str.tostring(adx3, ADXformatStructure), bgcolor = BGColor3, text_color = TxtColor3)
    table.cell(adxDisplay, 1, 0, "ADX 5m: " + str.tostring(adx5, ADXformatStructure), bgcolor = BGColor5, text_color = TxtColor5)
    table.cell(adxDisplay, 2, 0, "ADX 15m: " + str.tostring(adx15, ADXformatStructure), bgcolor = BGColor15, text_color = TxtColor15)
//
//RSI Divergence
//---------------------------Paramétrage des variables------------------------------

rb = input(2, 'How many right bars for pivots')
lb = input(15, 'How many left bars for pivots?')
sph = input(close, 'Pivot source for bear divs')
spl = input(close, 'Pivots source for bull divs')
len15 = input.int(14, ' RSI length', minval=1)
ob = input.int(70, 'RSI overbought level', minval=70, maxval=100)
os = input.int(30, 'RSI oversold level', minval=30, maxval=100)

showph = input(false, 'Show pivot highs?')
showpl = input(false, 'Show pivot lows?')
lvl = input.int(5, 'Lookback level for divs', options=[1, 2, 3, 4, 5])

//----------------------------definition des pivots et points d'ancrage-------------
ph = ta.pivothigh(sph, lb, rb)
pl = ta.pivotlow(spl, lb, rb)


hi0 = ta.valuewhen(ph, sph[rb], 0)
hi1 = ta.valuewhen(ph, sph[rb], 1)
hi2 = ta.valuewhen(ph, sph[rb], 2)
hi3 = ta.valuewhen(ph, sph[rb], 3)
hi4 = ta.valuewhen(ph, sph[rb], 4)
hi5 = ta.valuewhen(ph, sph[rb], 5)

lo0 = ta.valuewhen(pl, spl[rb], 0)
lo1 = ta.valuewhen(pl, spl[rb], 1)
lo2 = ta.valuewhen(pl, spl[rb], 2)
lo3 = ta.valuewhen(pl, spl[rb], 3)
lo4 = ta.valuewhen(pl, spl[rb], 4)
lo5 = ta.valuewhen(pl, spl[rb], 5)

lox0 = ta.valuewhen(pl, bar_index[rb], 0)
lox1 = ta.valuewhen(pl, bar_index[rb], 1)
lox2 = ta.valuewhen(pl, bar_index[rb], 2)
lox3 = ta.valuewhen(pl, bar_index[rb], 3)
lox4 = ta.valuewhen(pl, bar_index[rb], 4)
lox5 = ta.valuewhen(pl, bar_index[rb], 5)

hix0 = ta.valuewhen(ph, bar_index[rb], 0)
hix1 = ta.valuewhen(ph, bar_index[rb], 1)
hix2 = ta.valuewhen(ph, bar_index[rb], 2)
hix3 = ta.valuewhen(ph, bar_index[rb], 3)
hix4 = ta.valuewhen(ph, bar_index[rb], 4)
hix5 = ta.valuewhen(ph, bar_index[rb], 5)

rsi1 = ta.rsi(close, len15)

rh0 = ta.valuewhen(ph, rsi1[rb], 0)
rh1 = ta.valuewhen(ph, rsi1[rb], 1)
rh2 = ta.valuewhen(ph, rsi1[rb], 2)
rh3 = ta.valuewhen(ph, rsi1[rb], 3)
rh4 = ta.valuewhen(ph, rsi1[rb], 4)
rh5 = ta.valuewhen(ph, rsi1[rb], 5)

rl0 = ta.valuewhen(pl, rsi1[rb], 0)
rl1 = ta.valuewhen(pl, rsi1[rb], 1)
rl2 = ta.valuewhen(pl, rsi1[rb], 2)
rl3 = ta.valuewhen(pl, rsi1[rb], 3)
rl4 = ta.valuewhen(pl, rsi1[rb], 4)
rl5 = ta.valuewhen(pl, rsi1[rb], 5)
//-------------------------------definition des bull-bear divs-----------------

bull_div_1 = lo0 < lo1 and rl1 < rl0
bull_div_2 = lo0 < lo1 and lo0 < lo2 and rl2 < rl0 and rl2 < rl1 and lvl >= 2
bull_div_3 = lo0 < lo1 and lo0 < lo2 and lo0 < lo3 and rl3 < rl0 and rl3 < rl1 and rl3 < rl2 and lvl >= 3
bull_div_4 = lo0 < lo1 and lo0 < lo2 and lo0 < lo3 and lo0 < lo4 and rl4 < rl0 and rl4 < rl1 and rl4 < rl2 and rl4 < rl3 and lvl >= 4
bull_div_5 = lo0 < lo1 and lo0 < lo2 and lo0 < lo3 and lo0 < lo4 and lo0 < lo5 and rl5 < rl0 and rl5 < rl1 and rl5 < rl2 and rl5 < rl3 and rl5 < rl4 and lvl >= 5

bear_div_1 = hi0 > hi1 and rh1 > rh0
bear_div_2 = hi0 > hi1 and hi0 > hi2 and rh2 > rh0 and rh2 > rh1 and lvl >= 2
bear_div_3 = hi0 > hi1 and hi0 > hi2 and hi0 > hi3 and rh3 > rh0 and rh3 > rh1 and rh3 > rh2 and lvl >= 3
bear_div_4 = hi0 > hi1 and hi0 > hi2 and hi0 > hi3 and hi0 > hi4 and rh4 > rh0 and rh4 > rh1 and rh4 > rh2 and rh4 > rh3 and lvl >= 4
bear_div_5 = hi0 > hi1 and hi0 > hi2 and hi0 > hi3 and hi0 > hi4 and hi0 > hi5 and rh5 > rh0 and rh5 > rh1 and rh5 > rh2 and rh5 > rh3 and rh5 > rh4 and lvl >= 5


new_bull1 = bull_div_1 and not bull_div_1[1]
new_bull2 = bull_div_2 and not bull_div_2[1]
new_bull3 = bull_div_3 and not bull_div_3[1]
new_bull4 = bull_div_4 and not bull_div_4[1]
new_bull5 = bull_div_5 and not bull_div_5[1]

new_bear1 = bear_div_1 and not bear_div_1[1]
new_bear2 = bear_div_2 and not bear_div_2[1]
new_bear3 = bear_div_3 and not bear_div_3[1]
new_bear4 = bear_div_4 and not bear_div_4[1]
new_bear5 = bear_div_5 and not bear_div_5[1]

recall(x) =>
    ta.barssince(not na(x))



//---------------------apparence visuelle----------------------------------------

plotchar(pl and showpl, char='↑', color=color.new(color.orange, 0), offset=-rb, location=location.bottom, size=size.tiny)
plotchar(ph and showph, char='↓', color=color.new(color.aqua, 0), offset=-rb, location=location.top, size=size.tiny)

plotchar(new_bull1, char='↑', color=color.new(color.green, 0), offset=-rb, location=location.belowbar, size=size.tiny)
plotchar(new_bull2, char='↑', color=color.new(color.green, 0), offset=-rb, location=location.belowbar, size=size.tiny)
plotchar(new_bull3, char='↑', color=color.new(color.green, 0), offset=-rb, location=location.belowbar, size=size.tiny)
plotchar(new_bull4, char='↑', color=color.new(color.green, 0), offset=-rb, location=location.belowbar, size=size.tiny)
plotchar(new_bull5, char='↑', color=color.new(color.green, 0), offset=-rb, location=location.belowbar, size=size.tiny)


plotchar(new_bear1, char='↓', color=color.new(color.red, 0), offset=-rb, location=location.abovebar, size=size.tiny)
plotchar(new_bear2, char='↓', color=color.new(color.red, 0), offset=-rb, location=location.abovebar, size=size.tiny)
plotchar(new_bear3, char='↓', color=color.new(color.red, 0), offset=-rb, location=location.abovebar, size=size.tiny)
plotchar(new_bear4, char='↓', color=color.new(color.red, 0), offset=-rb, location=location.abovebar, size=size.tiny)
plotchar(new_bear5, char='↓', color=color.new(color.red, 0), offset=-rb, location=location.abovebar, size=size.tiny)

bull1 = line(na)
bull1 := new_bull1 and not new_bull2 and not new_bull3 and not new_bull4 and not new_bull5 ? line.new(lox0, lo0, lox1, lo1, color=color.green) : na
bull2 = line(na)
bull2 := new_bull2 and not new_bull3 and not new_bull4 and not new_bull5 ? line.new(lox0, lo0, lox2, lo2, color=color.green) : na
bull3 = line(na)
bull3 := new_bull3 and not new_bull4 and not new_bull5 ? line.new(lox0, lo0, lox3, lo3, color=color.green) : na
bull4 = line(na)
bull4 := new_bull4 and not new_bull5 ? line.new(lox0, lo0, lox4, lo4, color=color.green) : na
bull5 = line(na)
bull5 := new_bull5 ? line.new(lox0, lo0, lox5, lo5, color=color.green) : na

xbull21 = ta.valuewhen(recall(bull2) == 0, bar_index, 0) - ta.valuewhen(recall(bull1) == 0, bar_index, 0)
xbull31 = ta.valuewhen(recall(bull3) == 0, bar_index, 0) - ta.valuewhen(recall(bull1) == 0, bar_index, 0)
xbull41 = ta.valuewhen(recall(bull4) == 0, bar_index, 0) - ta.valuewhen(recall(bull1) == 0, bar_index, 0)
xbull51 = ta.valuewhen(recall(bull5) == 0, bar_index, 0) - ta.valuewhen(recall(bull1) == 0, bar_index, 0)
xbull32 = ta.valuewhen(recall(bull3) == 0, bar_index, 0) - ta.valuewhen(recall(bull2) == 0, bar_index, 0)
xbull42 = ta.valuewhen(recall(bull4) == 0, bar_index, 0) - ta.valuewhen(recall(bull2) == 0, bar_index, 0)
xbull52 = ta.valuewhen(recall(bull5) == 0, bar_index, 0) - ta.valuewhen(recall(bull2) == 0, bar_index, 0)
xbull43 = ta.valuewhen(recall(bull4) == 0, bar_index, 0) - ta.valuewhen(recall(bull3) == 0, bar_index, 0)
xbull53 = ta.valuewhen(recall(bull5) == 0, bar_index, 0) - ta.valuewhen(recall(bull3) == 0, bar_index, 0)
xbull54 = ta.valuewhen(recall(bull5) == 0, bar_index, 0) - ta.valuewhen(recall(bull4) == 0, bar_index, 0)

if new_bull2 and lo2 == ta.valuewhen(new_bull1, lo1, 0) and xbull21 >= 0
    line.delete(bull1[xbull21])
if new_bull3 and lo3 == ta.valuewhen(new_bull1, lo1, 0) and xbull31 >= 0
    line.delete(bull1[xbull31])
if new_bull4 and lo4 == ta.valuewhen(new_bull1, lo1, 0) and xbull41 >= 0
    line.delete(bull1[xbull41])
if new_bull5 and lo5 == ta.valuewhen(new_bull1, lo1, 0) and xbull51 >= 0
    line.delete(bull1[xbull51])
if new_bull3 and lo3 == ta.valuewhen(new_bull2, lo2, 0) and xbull32 >= 0
    line.delete(bull2[xbull32])
if new_bull4 and lo4 == ta.valuewhen(new_bull2, lo2, 0) and xbull42 >= 0
    line.delete(bull2[xbull42])
if new_bull5 and lo5 == ta.valuewhen(new_bull2, lo2, 0) and xbull52 >= 0
    line.delete(bull2[xbull52])
if new_bull4 and lo4 == ta.valuewhen(new_bull3, lo3, 0) and xbull43 >= 0
    line.delete(bull3[xbull43])
if new_bull5 and lo5 == ta.valuewhen(new_bull3, lo3, 0) and xbull53 >= 0
    line.delete(bull3[xbull53])
if new_bull5 and lo5 == ta.valuewhen(new_bull4, lo4, 0) and xbull54 >= 0
    line.delete(bull4[xbull54])


bear1 = line(na)
bear1 := new_bear1 and not new_bear2 and not new_bear3 and not new_bear4 and not new_bear5 ? line.new(hix0, hi0, hix1, hi1, color=color.red) : na
bear2 = line(na)
bear2 := new_bear2 and not new_bear3 and not new_bear4 and not new_bear5 ? line.new(hix0, hi0, hix2, hi2, color=color.red) : na
bear3 = line(na)
bear3 := new_bear3 and not new_bear4 and not new_bear5 ? line.new(hix0, hi0, hix3, hi3, color=color.red) : na
bear4 = line(na)
bear4 := new_bear4 and not new_bear5 ? line.new(hix0, hi0, hix4, hi4, color=color.red) : na
bear5 = line(na)
bear5 := new_bear5 ? line.new(hix0, hi0, hix5, hi5, color=color.red) : na


xbear21 = ta.valuewhen(recall(bear2) == 0, bar_index, 0) - ta.valuewhen(recall(bear1) == 0, bar_index, 0)
xbear31 = ta.valuewhen(recall(bear3) == 0, bar_index, 0) - ta.valuewhen(recall(bear1) == 0, bar_index, 0)
xbear41 = ta.valuewhen(recall(bear4) == 0, bar_index, 0) - ta.valuewhen(recall(bear1) == 0, bar_index, 0)
xbear51 = ta.valuewhen(recall(bear5) == 0, bar_index, 0) - ta.valuewhen(recall(bear1) == 0, bar_index, 0)
xbear32 = ta.valuewhen(recall(bear3) == 0, bar_index, 0) - ta.valuewhen(recall(bear2) == 0, bar_index, 0)
xbear42 = ta.valuewhen(recall(bear4) == 0, bar_index, 0) - ta.valuewhen(recall(bear2) == 0, bar_index, 0)
xbear52 = ta.valuewhen(recall(bear5) == 0, bar_index, 0) - ta.valuewhen(recall(bear2) == 0, bar_index, 0)
xbear43 = ta.valuewhen(recall(bear4) == 0, bar_index, 0) - ta.valuewhen(recall(bear3) == 0, bar_index, 0)
xbear53 = ta.valuewhen(recall(bear5) == 0, bar_index, 0) - ta.valuewhen(recall(bear3) == 0, bar_index, 0)
xbear54 = ta.valuewhen(recall(bear5) == 0, bar_index, 0) - ta.valuewhen(recall(bear4) == 0, bar_index, 0)

if new_bear2 and hi2 == ta.valuewhen(new_bear1, hi1, 0) and xbear21 >= 0
    line.delete(bear1[xbear21])
if new_bear3 and hi3 == ta.valuewhen(new_bear1, hi1, 0) and xbear31 >= 0
    line.delete(bear1[xbear31])
if new_bear4 and hi4 == ta.valuewhen(new_bear1, hi1, 0) and xbear41 >= 0
    line.delete(bear1[xbear41])
if new_bear5 and hi5 == ta.valuewhen(new_bear1, hi1, 0) and xbear51 >= 0
    line.delete(bear1[xbear51])
if new_bear3 and hi3 == ta.valuewhen(new_bear2, hi2, 0) and xbear32 >= 0
    line.delete(bear2[xbear32])
if new_bear4 and hi4 == ta.valuewhen(new_bear2, hi2, 0) and xbear42 >= 0
    line.delete(bear2[xbear42])
if new_bear5 and hi5 == ta.valuewhen(new_bear2, hi2, 0) and xbear52 >= 0
    line.delete(bear2[xbear52])
if new_bear4 and hi4 == ta.valuewhen(new_bear3, hi3, 0) and xbear43 >= 0
    line.delete(bear3[xbear43])
if new_bear5 and hi5 == ta.valuewhen(new_bear3, hi3, 0) and xbear53 >= 0
    line.delete(bear3[xbear53])
if new_bear5 and hi5 == ta.valuewhen(new_bear4, hi4, 0) and xbear54 >= 0
    line.delete(bear4[xbear54])
//
//Volume Profile

//.....................................................//

f_drawLabelX(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor, _size, _textalign, _tooltip) =>
    var id = label.new(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor, _size, _textalign, _tooltip)
    label.set_xy(id, _x, _y)
    label.set_text(id, _text)
    label.set_tooltip(id, _tooltip)
    label.set_textcolor(id, _textcolor)

// Functions  ----------------------------------------------------------------------------------- //
// ---------------------------------------------------------------------------------------------- //

// ---------------------------------------------------------------------------------------------- //
// Volume Profile (Price by Volume) / Volume Histogram ------------------------------------------ //

group_volume_profile    = 'Volume Profile / Price by Volume'
tooltip_volume_profile  = 'Volume Profile (also known as Price by Volume) is an charting study that displays trading activity over a specified time period at specific price levels'

volumeProfile     = input.bool(true, 'Volume Profile', group = group_volume_profile, tooltip = tooltip_volume_profile)
lookbackLength    = input.int(360, 'Lookback Length', minval = 10, maxval = 5000, step = 10 , group = group_volume_profile)
profileLevels     = input.int(100, 'Number of Rows' , minval = 10, maxval = 150 , step = 1  , group = group_volume_profile)
profileDisplay    = input.string('Up/Down', 'Volume', options = ['Up/Down', 'Total'], group = group_volume_profile)
upVolumeColor     = color.new(#1592e6, 30)
downVolumeColor   = color.new(#fbc123, 30)
totalVolumeColor  = color.new(#801922, 30)
backgroundColor   = color.new(#2962ff, 95)
pointOfControl    = input.bool(true, 'Show Point of Control', inline='PoC', group = group_volume_profile)
pocColor          = color.new(#ff0000, 0)
bullBearStr       = input.bool(true, 'Show Bull/Bear Volume Strength', inline='BB' , group = group_volume_profile)
bbStrUpColor      = color.new(#26a69a, 30)
bbStrDownColor    = color.new(#ef5350, 30)
priceLevels       = input.bool(true, 'Show Price Levels'                                    , group = group_volume_profile)
profilePlacement  = input.string('Right', 'Placment', options = ['Right', 'Left']           , group = group_volume_profile)
profileWidth      = input.int(75, 'Profile Width', minval = 21, maxval = 150                , group = group_volume_profile)
horizontalOffset  = input.int(25, 'Horizontal Offset', minval = 0 , maxval = 50             , group = group_volume_profile)

group_volume      = 'Volume Histogram'
tooltip_volume    = 'The Volume indicator is used to measure how much of a given financial asset has traded in a specific period of time'
volumeHistogram   = input.bool(true, 'Volume Histogram'                                       , group = group_volume, tooltip = tooltip_volume)
volumePlacement   = input.string('Top', 'Placment', options = ['Top', 'Bottom'], inline='VOL' , group = group_volume)
volumeHistHight   = 11 - input.int(8, 'Hight' , minval = 1, maxval = 10        , inline='VOL' , group = group_volume)
volumeMA          = input.bool(true, 'Volume MA, Length'                       , inline='vol2', group = group_volume)
volumeMALength    = input.int(21, '', minval = 1                               , inline='vol2', group = group_volume)
volumeUpColor     = color.new(#26a69a, 30)
volumeDownColor   = color.new(#ef5350, 30)
volumeMAColor     = color.new(#2962ff, 0)
volumeStorageT    = array.new_float(profileLevels + 1, 0.)
volumeStorageB    = array.new_float(profileLevels + 1, 0.)
var a_profile     = array.new_box()
var a_histogram   = array.new_line()
priceHighest      = ta.highest(high, lookbackLength)
priceLowest       = ta.lowest (low , lookbackLength)
priceStep         = (priceHighest - priceLowest) / profileLevels
priceChangeRate   = (priceHighest - priceLowest) / priceHighest 
barPriceLow       = low
barPriceHigh      = high
bullCandle        = close > open
nzVolume          = nz(volume)
volumeHighest     = ta.highest(nzVolume, lookbackLength)
volumeMARate      = nzVolume/ta.sma(nzVolume, volumeMALength)

if barstate.islast and nzVolume and volumeProfile
    if array.size(a_profile) > 0
        for i = 1 to array.size(a_profile)
            box.delete(array.shift(a_profile))
 
    if array.size(a_histogram) > 0
        for i = 1 to array.size(a_histogram)
            line.delete(array.shift(a_histogram))
            
    if priceLevels
        f_drawLabelX(bar_index + (profilePlacement == 'Right' ? profileWidth + horizontalOffset : 0), priceHighest, str.tostring(priceHighest, format.mintick), xloc.bar_index, yloc.price, color.new(upVolumeColor  , 89), profilePlacement == 'Left' and volumePlacement == 'Top'    ? label.style_label_left : label.style_label_down, upVolumeColor  , size.normal, text.align_left, 'Profile High - during last ' + str.tostring(lookbackLength) + ' bars\n %' + str.tostring((priceHighest - priceLowest) / priceLowest  * 100, '#.##') + ' higher than the Profile Low')
        f_drawLabelX(bar_index + (profilePlacement == 'Right' ? profileWidth + horizontalOffset : 0), priceLowest , str.tostring(priceLowest , format.mintick), xloc.bar_index, yloc.price, color.new(downVolumeColor, 89), profilePlacement == 'Left' and volumePlacement == 'Bottom' ? label.style_label_left : label.style_label_up  , downVolumeColor, size.normal, text.align_left, 'Profile Low - during last ' + str.tostring(lookbackLength) + ' bars\n %'  + str.tostring((priceHighest - priceLowest) / priceHighest * 100, '#.##') + ' lower than the Profile High')

    for barIndex = 0 to lookbackLength - 1
        level = 0
        for priceLevel = priceLowest to priceHighest by priceStep
            if barPriceHigh[barIndex] >= priceLevel and barPriceLow[barIndex] < priceLevel + priceStep
                array.set(volumeStorageT, level, array.get(volumeStorageT, level) + nzVolume[barIndex] * ((barPriceHigh[barIndex] - barPriceLow[barIndex]) == 0 ? 1 : priceStep / (barPriceHigh[barIndex] - barPriceLow[barIndex])) )
                
                if bullCandle[barIndex] and (profileDisplay == 'Up/Down' or bullBearStr)
                    array.set(volumeStorageB, level, array.get(volumeStorageB, level) + nzVolume[barIndex] * ((barPriceHigh[barIndex] - barPriceLow[barIndex]) == 0 ? 1 : priceStep / (barPriceHigh[barIndex] - barPriceLow[barIndex])) )
            level += 1
        
        if volumeHistogram and array.size(a_histogram) < 500
            array.push(a_histogram, line.new(bar_index[barIndex], volumePlacement == 'Top' ? priceHighest * (1 + priceChangeRate * .05) : priceLowest  * (1 - priceChangeRate * .05) , bar_index[barIndex], (volumePlacement == 'Top' ? priceHighest * (1 + priceChangeRate * .05) : priceLowest  * (1 - priceChangeRate * .05)) * (1 + ( volumePlacement == 'Top' ? 1 : -1) * nzVolume[barIndex] / volumeHighest * priceChangeRate / volumeHistHight), xloc.bar_index, extend.none, bullCandle[barIndex] ? volumeUpColor : volumeDownColor, line.style_solid, 2))
            
            if volumeMA
                array.push(a_histogram, line.new(bar_index[barIndex], (volumePlacement == 'Top' ? priceHighest * (1 + priceChangeRate * .05) : priceLowest  * (1 - priceChangeRate * .05)) * (1 + (volumePlacement == 'Top' ? 1 : -1) * nzVolume[barIndex] / volumeHighest * priceChangeRate / volumeHistHight / volumeMARate[barIndex]), bar_index[barIndex + 1], (volumePlacement == 'Top' ? priceHighest * (1 + priceChangeRate * .05) : priceLowest  * (1 - priceChangeRate * .05)) * (1 + (volumePlacement == 'Top' ? 1 : -1) * nzVolume[barIndex + 1] / volumeHighest * priceChangeRate / volumeHistHight / volumeMARate[barIndex + 1]), xloc.bar_index, extend.none, volumeMAColor, line.style_solid, 2))

    array.push(a_profile, box.new(bar_index - lookbackLength + 1, priceLowest, bar_index + (profilePlacement == 'Right' ? profileWidth + horizontalOffset : 0), priceHighest, backgroundColor, 1, line.style_dotted, bgcolor = backgroundColor ))
    
    if pointOfControl
        array.push(a_profile, box.new(bar_index - lookbackLength + 1, priceLowest + (array.indexof(volumeStorageT, array.max(volumeStorageT)) + .40) * priceStep, bar_index + (profilePlacement == 'Right' ? profileWidth : 0), priceLowest + (array.indexof(volumeStorageT, array.max(volumeStorageT)) + .60) * priceStep, pocColor, bgcolor = pocColor ))
        
        if priceLevels
            f_drawLabelX(bar_index + (profilePlacement == 'Right' ? horizontalOffset + 5 : 7), priceLowest + (array.indexof(volumeStorageT, array.max(volumeStorageT)) + .5) * priceStep, str.tostring(priceLowest + (array.indexof(volumeStorageT, array.max(volumeStorageT)) + .5) * priceStep, format.mintick), xloc.bar_index, yloc.price, color.new(pocColor, 89), (profilePlacement == 'Right' ? label.style_label_up : label.style_label_left), color.new(pocColor, 0), size.normal, text.align_left, 'Point Of Control Price')

    for level = 0 to profileLevels - 1
        levelColor = profileDisplay == 'Up/Down' ? downVolumeColor : totalVolumeColor
        startBoxIndex = profilePlacement == 'Right' ? bar_index + profileWidth + horizontalOffset - int(array.get(volumeStorageT, level) / array.max(volumeStorageT) * (profileWidth - 9)) : bar_index - lookbackLength + 1
        endBoxIndex   = profilePlacement == 'Right' ? bar_index + profileWidth + horizontalOffset:  startBoxIndex + int( array.get(volumeStorageT, level) / array.max(volumeStorageT) * (profileWidth - 9))
        array.push(a_profile, box.new(startBoxIndex, priceLowest + (level + 0.1) * priceStep, endBoxIndex, priceLowest + (level + 0.9) * priceStep, levelColor, bgcolor = levelColor ))

        if profileDisplay == 'Up/Down'
            startBoxIndex := profilePlacement == 'Right' ? bar_index + profileWidth + horizontalOffset - int(array.get(volumeStorageB, level) / array.max(volumeStorageB) * (profileWidth - 9) / 2) : bar_index - lookbackLength + 1
            endBoxIndex   := profilePlacement == 'Right' ? bar_index + profileWidth + horizontalOffset:  startBoxIndex + int( array.get(volumeStorageB, level) / array.max(volumeStorageB) * (profileWidth - 9) / 2)
            array.push(a_profile, box.new(startBoxIndex, priceLowest + (level + 0.1) * priceStep, endBoxIndex, priceLowest + (level + 0.9) * priceStep, upVolumeColor, bgcolor = upVolumeColor ))
        
        if bullBearStr
            bullBearPower  = 2 * array.get(volumeStorageB, level) - array.get(volumeStorageT, level)
            startBoxIndex := profilePlacement == 'Right' ? bar_index + profileWidth + 1 + horizontalOffset + (bullBearPower > 0 ? 1 : -1) * int(bullBearPower / array.max(volumeStorageT) * (profileWidth - 9) * 1.75) : bar_index - lookbackLength
            endBoxIndex   := profilePlacement == 'Right' ? bar_index + profileWidth + 1 + horizontalOffset:  startBoxIndex + (bullBearPower > 0 ? -1 : 1) * int(bullBearPower / array.max(volumeStorageT) * (profileWidth - 9) * 1.75 )
            array.push(a_profile, box.new(startBoxIndex, priceLowest + (level + 0.1) * priceStep, endBoxIndex, priceLowest + (level + 0.9) * priceStep, bullBearPower > 0 ? bbStrUpColor : bbStrDownColor, bgcolor = bullBearPower > 0 ? bbStrUpColor : bbStrDownColor ))

// Volume Profile (Price by Volume) / Volume Histogram ------------------------------------------ //
// ---------------------------------------------------------------------------------------------- //
// Volume Weighted Colored Bars ----------------------------------------------------------------- //

group_volume_weighted_colored_bars      = 'Volume Weighted Colored Bars'
vwcb = input.bool(false, 'Volume Weighted Colored Bars', group=group_volume_weighted_colored_bars, tooltip='Colors bars based on the bar\'s volume relative to volume moving average')
vSMA = ta.sma(nzVolume, input.int(89, 'Volume Moving Average Length', group=group_volume_weighted_colored_bars))

barcolor(vwcb and nzVolume ? nzVolume > vSMA * input.float(1.618, 'Higher Theshold', minval=1., step=.1, group=group_volume_weighted_colored_bars) ? bullCandle ? color.new(#006400,0) : color.new(#910000,0) : nzVolume < vSMA * input.float(0.618, 'Lower Theshold', minval=.1, step=.1, group=group_volume_weighted_colored_bars) ? bullCandle ? color.new(#7FFFD4,0) : color.new(#FF9800,0) : bullCandle ? color.new(color.green,0) : color.new(color.red,0) : na, title='Volume Weighted Colored Bars')

// Volume Weighted Colored Bars ----------------------------------------------------------------- //
// ---------------------------------------------------------------------------------------------- //

var table logo = table.new(position.bottom_right, 1, 1)
if barstate.islast
    table.cell(logo, 0, 0, '☼☾  ', text_size=size.normal, text_color=color.new(color.teal,0))
//
//Settlement

// === INPUTS
useDaily = input(true, title='Use Daily Data to Calculate HV (default), otherwise chart TF')
LookBack = input.int(21, minval=1)
annual = input.int(252, minval=1)
DaystoExpire_ = input.int(defval=0, minval=0, title='Calender Days to Expiry (0=Auto, default)')
src_ = input(close, title='Settlement Source (close=default)')
sLength_ = input.int(1, minval=1, title='Settlement Volume Weighted Average Length (1=Use end of day)')
//
showset  = input(title="Settlement", defval=true, group='Settlement')
stddev1 = input(true, title='Display 1x Standard Deviation Levels', group='Settlement')
stddev2 = input(false, title='Display 2x Standard Deviation Levels',group='Settlement')
stddev3 = input(false, title='Display 3x Standard Deviation Levels',group='Settlement')
pivotNow = input(false, title='Display Only Todays Deviation Levels',group='Settlement')
showstd1 = input(title="Dev1 Labels", defval=true, group='Settlement')
showstd2 = input(title="Dev2 Labels", defval=false,group='Settlement')
showstd3 = input(title="Dev3 Labels", defval=false, group='Settlement')


// 
// === /INPUTs
dodgerblue = #1E90FF
//
// Test for new Daily Session or start of new month for Daily.
sLength = timeframe.isintraday ? sLength_ : 1
nstart = request.security(syminfo.tickerid, 'D', bar_index, barmerge.gaps_off, barmerge.lookahead_on)
start21 = request.security(syminfo.tickerid, 'D', time, barmerge.gaps_off, barmerge.lookahead_on)
first = request.security(syminfo.tickerid, 'D', ta.valuewhen(barstate.islast, time, 0), barmerge.gaps_off, barmerge.lookahead_on)

nohist = nstart <= math.max(sLength, LookBack) + 1

change_1 = ta.change(start21)
newDay = nohist ? false : timeframe.isintraday ? change_1 : dayofmonth(time) < dayofmonth(time[1])


// Calculate Annualised Volatility
hv = 0.0
stdev_1 = ta.stdev(math.log(src_ / src_[1]), LookBack)
security_1 = request.security(syminfo.tickerid, 'D', stdev_1 * math.sqrt(annual), barmerge.gaps_off, barmerge.lookahead_on)
stdev_2 = ta.stdev(math.log(src_ / src_[1]), LookBack)
hv_ = useDaily ? security_1 : stdev_2 * math.sqrt(annual)
hv := newDay ? hv_ : nz(hv[1], hv_)
hinow = high
hinow := newDay ? high : high > hinow[1] ? high : hinow[1]
lonow = low
lonow := newDay ? low : low < lonow[1] ? low : lonow[1]

prevhi = ta.valuewhen(newDay, hinow[1], 0)
prevlo = ta.valuewhen(newDay, lonow[1], 0)

// get the Daily Settlement 
valuewhen_1 = ta.valuewhen(start21[1] <= time, src_, 0)
vwma_1 = ta.vwma(src_[1], sLength)
settlement = sLength == 1 ? valuewhen_1 : vwma_1
settlement := newDay ? settlement : nz(settlement[1], open[1])



firstDay = dayofmonth(start21) == dayofmonth(first) and month(start21) == month(first) and year(start21) == year(first)
stdhv = 0.0
DaystoExpire = DaystoExpire_ == 0 ? timeframe.isintraday ? useDaily ? 1 : math.min(annual, 1440 / timeframe.multiplier) : LookBack : DaystoExpire_
stdhv := newDay ? settlement * hv * math.sqrt(DaystoExpire / annual) : nz(stdhv[1])

// calculate StdDev lines ratios.
stdhv05 = stdhv * 0.5
stdhv07 = stdhv * 0.7
stdhv1 = stdhv
stdhv15 = stdhv * 1.5
stdhv2 = stdhv * 2.0
stdhv25 = stdhv * 2.5


Stdhv05u = settlement + stdhv05
Stdhv05d = settlement - stdhv05
Stdhv07u = settlement + stdhv07
Stdhv07d = settlement - stdhv07
Stdhv1u  = settlement + stdhv1
Stdhv1d  = settlement - stdhv1
Stdhv15u = settlement + stdhv15
Stdhv15d = settlement - stdhv15
Stdhv2u  = settlement + stdhv2
Stdhv2d  = settlement - stdhv2
Stdhv25u = settlement + stdhv25
Stdhv25d = settlement - stdhv25



// Plot the StdDev Levels for all Days.

SettleM = plot(not nohist and showset and stddev1 and (not pivotNow or firstDay) and not newDay ? settlement : na, color=color.new(#ec186d, 0), title='Settlement', linewidth=2, style=plot.style_linebr)
stdhv05u = plot(not nohist and showset and stddev1 and (not pivotNow or firstDay) and not newDay ? settlement + stdhv05 : na, color=color.new(color.orange, 20), title='+0.5 SD', linewidth=1, style=plot.style_linebr)
stdhv05d = plot(not nohist and showset and stddev1 and (not pivotNow or firstDay) and not newDay ? settlement - stdhv05 : na, color=color.new(color.orange, 20), title='-0.5 SD', linewidth=1, style=plot.style_linebr)
stdhv07u = plot(not nohist and showset and stddev1 and (not pivotNow or firstDay) and not newDay ? settlement + stdhv07 : na, color=color.new(color.red, 20), title='+0.7 SD', linewidth=1, style=plot.style_linebr)
stdhv07d = plot(not nohist and showset and stddev1 and (not pivotNow or firstDay) and not newDay ? settlement - stdhv07 : na, color=color.new(color.red, 20), title='-0.7 SD', linewidth=1, style=plot.style_linebr)
stdhv1u = plot(not nohist and showset and stddev1 and (not pivotNow or firstDay) and not newDay ? settlement + stdhv1 : na, color=color.new(color.lime, 20), title='+1 SD', linewidth=3, style=plot.style_linebr)
stdhv1d = plot(not nohist and showset and stddev1 and (not pivotNow or firstDay) and not newDay ? settlement - stdhv1 : na, color=color.new(color.lime, 20), title='-1 SD', linewidth=3, style=plot.style_linebr)
stdhv15u = plot(not nohist and showset and stddev2 and (not pivotNow or firstDay) and not newDay ? settlement + stdhv15 : na, color=color.new(color.green, 20), title='+1.5 SD', linewidth=1, style=plot.style_linebr)
stdhv15d = plot(not nohist and showset and stddev2 and (not pivotNow or firstDay) and not newDay ? settlement - stdhv15 : na, color=color.new(color.green, 20), title='-1.5 SD', linewidth=1, style=plot.style_linebr)
stdhv2u = plot(not nohist and showset and stddev2 and (not pivotNow or firstDay) and not newDay ? settlement + stdhv2 : na, color=color.new(color.blue, 20), title='+2 SD', linewidth=3, style=plot.style_linebr)
stdhv2d = plot(not nohist and showset and stddev2 and (not pivotNow or firstDay) and not newDay ? settlement - stdhv2 : na, color=color.new(color.blue, 20), title='-2 SD', linewidth=3, style=plot.style_linebr)
stdhv25u = plot(not nohist and showset and stddev3 and (not pivotNow or firstDay) and not newDay ? settlement + stdhv25 : na, color=color.new(color.aqua, 20), title='+2.5 SD', linewidth=1, style=plot.style_linebr)
stdhv25d = plot(not nohist and showset and stddev3 and (not pivotNow or firstDay) and not newDay ? settlement - stdhv25 : na, color=color.new(color.aqua, 20), title='-2.5 SD', linewidth=1, style=plot.style_linebr)

//Show Settlement

if showset
    if stddev1
        if settlement
            settlement = label.new(start21, settlement, text='Settlement', xloc=xloc.bar_time, textcolor=color.new(#ec186d,0), style=label.style_none)
            label.delete(settlement[1])
        if Stdhv05u
            Stdhv05u = label.new(start21, Stdhv05u, text='+0.5', xloc=xloc.bar_time, textcolor=color.new(color.orange,0), style=label.style_none)
            label.delete(Stdhv05u[1])
        if Stdhv05d
            Stdhv05d = label.new(start21, Stdhv05d, text='-0.5', xloc=xloc.bar_time, textcolor=color.new(color.orange,0), style=label.style_none)
            label.delete(Stdhv05d[1])
        if Stdhv07u
            Stdhv07u = label.new(start21, Stdhv07u, text='+0.7', xloc=xloc.bar_time, textcolor=color.new(color.red,0), style=label.style_none)
            label.delete(Stdhv07u[1])
        if Stdhv07d
            Stdhv07d = label.new(start21, Stdhv07d, text='-0.7', xloc=xloc.bar_time, textcolor=color.new(color.red,0), style=label.style_none)
            label.delete(Stdhv07d[1])
        if Stdhv1u
            Stdhv1u = label.new(start21, Stdhv1u, text='+1.0', xloc=xloc.bar_time, textcolor=color.new(color.lime,10), style=label.style_none)
            label.delete(Stdhv1u[1])
        if Stdhv1d
            Stdhv1d = label.new(start21, Stdhv1d, text='-1.0', xloc=xloc.bar_time, textcolor=color.new(color.lime,10), style=label.style_none)
            label.delete(Stdhv1d[1])
    if showstd2
        if Stdhv15u
            Stdhv15u = label.new(start21, Stdhv15u, text='+1.5', xloc=xloc.bar_time, textcolor=color.new(color.green,10), style=label.style_none)
            label.delete(Stdhv15u[1])
        if Stdhv15d
            Stdhv15d = label.new(start21, Stdhv15d, text='-1.5', xloc=xloc.bar_time, textcolor=color.new(color.green,10), style=label.style_none)
            label.delete(Stdhv15d[1])
        if Stdhv2u
            Stdhv2u = label.new(start21, Stdhv2u, text='+2.0', xloc=xloc.bar_time, textcolor=color.new(color.blue,10), style=label.style_none)
            label.delete(Stdhv2u[1])
        if Stdhv2d
            Stdhv2d = label.new(start21, Stdhv2d, text='-2.0', xloc=xloc.bar_time, textcolor=color.new(color.blue,10), style=label.style_none)
            label.delete(Stdhv2d[1])
    if showstd3
        if Stdhv25u
            Stdhv25u = label.new(start21, Stdhv25u, text='+2.5', xloc=xloc.bar_time, textcolor=color.new(color.aqua,10), style=label.style_none)
            label.delete(Stdhv25u[1])
        if Stdhv25d
            Stdhv25d = label.new(start21, Stdhv25d, text='-2.5', xloc=xloc.bar_time, textcolor=color.new(color.aqua,10), style=label.style_none)
            label.delete(Stdhv25d[1])
//
//Offset MA

showoffsetma = input(title='EMA Offset', defval=false)
len12= input.int(3, minval=1, title="Length")
src12 = input(close, title="Source")
offset = input.int(title="Offset", defval=2, minval=-500, maxval=500)
out12 = ta.ema(src12, len12)
plot(showoffsetma ? out12 : na, title="EMA", color=color.blue, linewidth=2, offset=offset)

ma(source, length, type) =>
    switch type
        "SMA" => ta.sma(source, length)
        "EMA" => ta.ema(source, length)
        "SMMA (RMA)" => ta.rma(source, length)
        "WMA" => ta.wma(source, length)
        "VWMA" => ta.vwma(source, length)

typeMA = input.string(title = "Method", defval = "SMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="Smoothing")
smoothingLength = input.int(title = "Length", defval = 5, minval = 1, maxval = 100, group="Smoothing")

smoothingLine = ma(out12, smoothingLength, typeMA)
plot(smoothingLine, title="Smoothing Line", color=#f37f20, offset=offset, display=display.none)
//